package com.cjj.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 共享资源对象
 */
class Res2 {
    public String name;
    public String sex;
    public boolean flag = false;
    public Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
}

/**
 * 写入线程
 */
class InputThread2 extends Thread {

    public Res2 res;

    public InputThread2(Res2 res) {
        this.res = res;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            try {
                res.lock.lock();
                if (res.flag) {
                    try {
                        res.condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (count == 0) {
                    res.name = "ccc-ju";
                    res.sex = "男";
                } else {
                    res.name = "xiaofang";
                    res.sex = "女";
                }
                count = (count + 1) % 2;
                res.flag = true;
                // 释放锁
                res.condition.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                res.lock.unlock();
            }
        }
    }
}

/**
 * 读线程
 */
class OutputThread2 extends Thread {
    public Res2 res;

    public OutputThread2(Res2 res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            try {
                res.lock.lock();
                if (!res.flag) {
                    res.condition.await();
                }
                System.out.println(res.name + "----" + res.sex);
                res.flag = false;
                res.condition.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                res.lock.unlock();
            }
        }

    }
}

/**
 * 第一个线程(input)用户，另一个线程读取(out)用户，实现写一个读一个操作
 *
 * @ClassName Thread_01
 * @Date 2021/07/17 15:48:49
 * @Created by ccc-j
 * @email ccc-ju@outlook.com
 */
public class Lock_01 {

    public static void main(String[] args) {
        Res2 res = new Res2();
        InputThread2 inputThread = new InputThread2(res);
        OutputThread2 outputThread = new OutputThread2(res);
        inputThread.start();
        outputThread.start();
    }

}
